package cn.com.common.job.task;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasCaminfoForecastEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStationinfoForecastEntity;
import cn.com.gas.entity.GasStationinfoForecastMonthEntity;
import cn.com.gas.service.GasCaminfoForecastService;
import cn.com.gas.service.GasStationinfoForecastMonthService;
import cn.com.gas.service.GasStationinfoForecastService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.system.entity.SysParameterEntity;
import cn.com.system.service.SysParameterService;
import cn.com.thirdparty.entity.ProvinceGasStationinfoForecastMonthEntity;
import cn.com.thirdparty.mapper.ProvinceGasStationinfoForecastMonthMapper;
import cn.com.util.TsBqUtils;

/**
 * 月预估
 * 
 * @author shaochangyang
 *
 */
@Component("gasStationMonthProcessTask")
@DisallowConcurrentExecution
public class GasStationMonthProcessTask {

	@Value("${gasstation.timedTask.gasStationMonthProcessTask}")
	private String gasStationMonthProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SysParameterService sysParameterService;
	@Autowired
	private GasStationinfoService stationinfoService;
	@Autowired
	private GasStationinfoForecastService stationinfoForecastService;
	@Autowired
	private GasStationinfoForecastMonthService gasStationinfoForecastMonthService;
	@Autowired
	private GasCaminfoForecastService gasCaminfoForecastService;
	
	@Autowired
	private ProvinceGasStationinfoForecastMonthMapper provinceGasStationinfoForecastMonthMapper;
	
	
	public void run(String params) throws Exception {
		logger.debug("gasStationMonthProcessTask定时任务正在执行，参数为：{}", params);
		logger.debug("application参数为gasStationMonthProcessTask：{}", gasStationMonthProcessTask);

		if (gasStationMonthProcessTask.equals(Constants.JOB_STOP)) {
			logger.debug("application配置文件控制不执行gasStationMonthProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasStationMonthProcessTask定时任务");
		}

		LocalDate currentDate = LocalDate.now();
        LocalDate lastMonthDate = currentDate.minusMonths(1);
 
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String month = lastMonthDate.format(formatter);

		if (TsBqUtils.isNotNull(params)) {
			
			String[] _paramsArr = params.split("_");
			
			for (String _params : _paramsArr) {
				
				String _year = _params.substring(0, 4);
				String _month = _params.substring(4,6);
				
				logger.debug("gasStationMonthProcessTask定时任务正在执行，加工日期：{}", _params);
				handleData(_year + "-" + _month);
				logger.debug("gasStationMonthProcessTask定时任务正在执行，加工完成：{}", _params);

			}

		} else {
			logger.debug("gasStationMonthProcessTask定时任务正在执行，加工日期：{}", month);
			handleData(month);
			logger.debug("gasStationMonthProcessTask定时任务正在执行，加工完成：{}", month);

		}

	}
	// 处理数据
	private String handleData(String month) {
		
		String pushFlag = "N";
		SysParameterEntity sysParameterEntity = sysParameterService.getById("parameter106");
		if(TsBqUtils.isNotNull(sysParameterEntity)){
			pushFlag = sysParameterEntity.getParameter();
		}
		logger.debug("gasStationMonthProcessTask给省平台推送标志，标志为：{}", pushFlag);
		
		YearMonth yearMonth = YearMonth.of(Integer.parseInt(month.substring(0, 4)), Integer.parseInt(month.substring(5, 7)));
        int daysInMonth = yearMonth.lengthOfMonth();
		
		// stationinfoForecastService
		
		LambdaQueryWrapper<GasStationinfoForecastEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.like(GasStationinfoForecastEntity::getTime, month);
		List<GasStationinfoForecastEntity> list = stationinfoForecastService.list(queryWrapper);
		Map<String, List<GasStationinfoForecastEntity>> groupedItems = list.stream()
				.collect(Collectors.groupingBy(item -> item.getStationinfoId()));
		
		List<GasStationinfoForecastMonthEntity> gasStationinfoForecastMonthEntityList = new ArrayList<>();
		groupedItems.forEach((category, itemsInCategory) -> {
			int size = itemsInCategory.size();
			BigDecimal[] forecastValueBd = { new BigDecimal(0) };
			
			BigDecimal[] amountGasolineBd = { new BigDecimal(0) }; // 汽油数量
			BigDecimal[] amountDieselBd = { new BigDecimal(0) }; // 柴油数量
			BigDecimal[] amountPrivateBd = { new BigDecimal(0) };//  民营数量
			BigDecimal[] amountPublicBd = { new BigDecimal(0) }; // 三桶油数量
			BigDecimal[] saleGasolineBd = { new BigDecimal(0) }; // 汽油金额
			BigDecimal[] saleDieselBd = { new BigDecimal(0) }; // 柴油金额
			BigDecimal[] salePrivateBd = { new BigDecimal(0) }; // 民营金额
			BigDecimal[] salePublicBd = { new BigDecimal(0) }; // 三桶油金额
			
			BigDecimal[] gatherValueBd = { new BigDecimal(0) }; // 三桶油金额
			
			BigDecimal forecastAveValue = new BigDecimal(0);
			
			// BigDecimal forecastCompensationValue = new BigDecimal(0); //计算平均值
			
			int i = 0;
			// daysInMonth
			// 计算合计
			itemsInCategory.forEach(item -> {
				String forecastValue = item.getForecastValue();
				String forecastValue1 = item.getForecastValue1();
				String gatherValue = item.getGatherValue();
				
				String amountGasoline = item.getAmountGasoline(); // 汽油数量
				String amountDiesel = item.getAmountDiesel(); // 柴油数量
				String amountPrivate = item.getAmountPrivate();//  民营数量
				String amountPublic = item.getAmountPublic(); // 三桶油数量
				String saleGasoline = item.getSaleGasoline(); // 汽油金额
				String saleDiesel = item.getSaleDiesel(); // 柴油金额
				String salePrivate = item.getSalePrivate(); // 民营金额
				String salePublic = item.getSalePublic(); // 三桶油金额
				
				
				if(TsBqUtils.isNotNull(forecastValue1)){
					forecastValueBd[0] = forecastValueBd[0].add(new BigDecimal(forecastValue1));
				}else{
					forecastValueBd[0] = forecastValueBd[0].add(new BigDecimal(forecastValue));
				}
				if(TsBqUtils.isNotNull(amountGasoline)){
					amountGasolineBd[0] = amountGasolineBd[0].add(new BigDecimal(amountGasoline));  // 汽油数量
				}
				if(TsBqUtils.isNotNull(amountDiesel)){
					amountDieselBd[0] = amountDieselBd[0].add(new BigDecimal(amountDiesel));  // 柴油数量
				}
				if(TsBqUtils.isNotNull(amountPrivate)){
					amountPrivateBd[0] = amountPrivateBd[0].add(new BigDecimal(amountPrivate)); //  民营数量
				}
				if(TsBqUtils.isNotNull(amountPublic)){
					amountPublicBd[0] = amountPublicBd[0].add(new BigDecimal(amountPublic)); // 三桶油数量
				}
				if(TsBqUtils.isNotNull(saleGasoline)){
					saleGasolineBd[0] = saleGasolineBd[0].add(new BigDecimal(saleGasoline));  // 汽油金额
				}
				if(TsBqUtils.isNotNull(saleDiesel)){
					saleDieselBd[0] = saleDieselBd[0].add(new BigDecimal(saleDiesel)); // 柴油金额
				}
				if(TsBqUtils.isNotNull(salePrivate)){
					salePrivateBd[0] = salePrivateBd[0].add(new BigDecimal(salePrivate));  // 民营金额
				}
				if(TsBqUtils.isNotNull(salePublic)){
					salePublicBd[0] = salePublicBd[0].add(new BigDecimal(salePublic)); // 三桶油金额
				}
				if(TsBqUtils.isNotNull(gatherValue)){
					gatherValueBd[0] = gatherValueBd[0].add(new BigDecimal(gatherValue)); // 三桶油金额
				}
				
				
			});
			
			// 平均值
			if (forecastValueBd[0].compareTo(BigDecimal.ZERO) != 0) {
				forecastAveValue = forecastValueBd[0].divide(new BigDecimal(size), 2, RoundingMode.HALF_UP);
				i = daysInMonth - size;
				if(i > 0){
					// 数据补偿
			        BigDecimal forecastCompensationDb = forecastAveValue.multiply(new BigDecimal(i));
			        forecastValueBd[0] = forecastValueBd[0].add(forecastCompensationDb);
			        
				}
			}
			
			GasStationinfoForecastMonthEntity stationinfoForecastMonth = new GasStationinfoForecastMonthEntity();
			GasStationinfoEntity stationinfoEntity = stationinfoService.getById(category);
			
			stationinfoForecastMonth.setTime(month);
			stationinfoForecastMonth.setStationinfoId(category);
			stationinfoForecastMonth.setTaxorgcode(stationinfoEntity.getTaxorgcode());
			stationinfoForecastMonth.setForecastValue(forecastValueBd[0].toString());
			stationinfoForecastMonth.setForecastAveValue(forecastAveValue.toString());
			stationinfoForecastMonth.setCompensationDay(i + "");
			
			stationinfoForecastMonth.setGatherDay(size + ""); // 采集天数
			
			
			stationinfoForecastMonth.setAmountGasoline(amountGasolineBd[0].toString()); // 汽油数量
			stationinfoForecastMonth.setAmountDiesel(amountDieselBd[0].toString()); // 柴油数量
			stationinfoForecastMonth.setAmountPrivate(amountPrivateBd[0].toString());//  民营数量
			stationinfoForecastMonth.setAmountPublic(amountPublicBd[0].toString()); // 三桶油数量
			stationinfoForecastMonth.setSaleGasoline(saleGasolineBd[0].toString()); // 汽油金额
			stationinfoForecastMonth.setSaleDiesel(saleDieselBd[0].toString()); // 柴油金额
			stationinfoForecastMonth.setSalePrivate(salePrivateBd[0].toString()); // 民营金额
			stationinfoForecastMonth.setSalePublic(salePublicBd[0].toString()); // 三桶油金额
			
			stationinfoForecastMonth.setGatherValue(gatherValueBd[0].toString());
			
			// 计算离线时间 stationinfoForecastMonth
			// (select sum(d.offline_time) from gas_caminfo_forecast d where d.time like '2025-02%' and d.stationinfo_id = a.stationinfo_id)
			
			/*LambdaQueryWrapper<GasCaminfoForecastEntity> caminfoForecastQueryWrapper = Wrappers.lambdaQuery();
			queryWrapper.like(GasCaminfoForecastEntity::getTime, month);
			
			gasCaminfoForecastService.*/
			
			stationinfoForecastMonth.setDeleted(Constants.DATA_NOT_DELETED);
			stationinfoForecastMonth.setCreateId("job");
			stationinfoForecastMonth.setCreateTime(new Date());
			
			gasStationinfoForecastMonthEntityList.add(stationinfoForecastMonth);
			
		});
		// 更新数据
		
		if(TsBqUtils.isNotNull(gasStationinfoForecastMonthEntityList)){
			for (GasStationinfoForecastMonthEntity gasStationinfoForecastMonthEntity : gasStationinfoForecastMonthEntityList) {
				// 处理离线时间
				String stationinfoId = gasStationinfoForecastMonthEntity.getStationinfoId();
				String time = gasStationinfoForecastMonthEntity.getTime();
				LambdaQueryWrapper<GasCaminfoForecastEntity> caminfoForecastQueryWrapper = Wrappers.lambdaQuery();
				caminfoForecastQueryWrapper.like(GasCaminfoForecastEntity::getTime, time);
				caminfoForecastQueryWrapper.like(GasCaminfoForecastEntity::getStationinfoId, stationinfoId);
				
				List<GasCaminfoForecastEntity> caminfoForecastList = gasCaminfoForecastService.list(caminfoForecastQueryWrapper);
				BigDecimal offlineTimeBigDecimal = new BigDecimal(0);
				for (GasCaminfoForecastEntity gasCaminfoForecastEntity : caminfoForecastList) {
					
					String offlineTime = gasCaminfoForecastEntity.getOfflineTime();
					if(TsBqUtils.isNotNull(offlineTime)){
						offlineTimeBigDecimal = offlineTimeBigDecimal.add(new BigDecimal(offlineTime));
					}
				}
				
				gasStationinfoForecastMonthEntity.setOfflineTime((offlineTimeBigDecimal.divide(new BigDecimal(60), 2, BigDecimal.ROUND_HALF_UP)).toString());
				
				// 删除数据
				gasStationinfoForecastMonthService.realRemoveById(gasStationinfoForecastMonthEntity);
				gasStationinfoForecastMonthService.save(gasStationinfoForecastMonthEntity);

				try {
					if(pushFlag.equals("Y")){
						// 类转转换 推送
						ProvinceGasStationinfoForecastMonthEntity entity = new ProvinceGasStationinfoForecastMonthEntity();
						BeanUtils.copyProperties(gasStationinfoForecastMonthEntity, entity);
						provinceGasStationinfoForecastMonthMapper.realRemoveById(entity);
						provinceGasStationinfoForecastMonthMapper.insert(entity);
						
					}
					
				} catch (Exception e) {
					logger.error("推送省平台异常：" + e.getMessage());
				}
				
				
			}
			
		}
		return "";
	}
	
}
